import json
import os
from typing import List, Dict, Any, Optional


class ConfigManager:
    """管理ChromaDB连接配置的类"""
    
    def __init__(self, config_file: str = "connect_config.json"):
        """
        初始化配置管理器
        
        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self.connections = self._load_config()
    
    def _load_config(self) -> List[Dict[str, Any]]:
        """
        从配置文件加载连接配置
        
        Returns:
            连接配置列表
        """
        if not os.path.exists(self.config_file):
            return []
        
        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"加载配置文件出错: {e}")
            return []
    
    def save_config(self) -> bool:
        """
        保存连接配置到文件
        
        Returns:
            是否保存成功
        """
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.connections, f, ensure_ascii=False, indent=4)
            return True
        except Exception as e:
            print(f"保存配置文件出错: {e}")
            return False
    
    def get_connections(self) -> List[Dict[str, Any]]:
        """
        获取所有连接配置
        
        Returns:
            连接配置列表
        """
        return self.connections
    
    def get_connection(self, name: str) -> Optional[Dict[str, Any]]:
        """
        根据名称获取连接配置
        
        Args:
            name: 连接名称
            
        Returns:
            连接配置，如果不存在则返回None
        """
        for conn in self.connections:
            if conn.get('name') == name:
                return conn
        return None
    
    def add_connection(self, connection: Dict[str, Any]) -> bool:
        """
        添加新的连接配置
        
        Args:
            connection: 连接配置
            
        Returns:
            是否添加成功
        """
        # 检查是否已存在同名连接
        if self.get_connection(connection.get('name')):
            return False
        
        self.connections.append(connection)
        return self.save_config()
    
    def update_connection(self, name: str, connection: Dict[str, Any]) -> bool:
        """
        更新连接配置
        
        Args:
            name: 原连接名称
            connection: 新的连接配置
            
        Returns:
            是否更新成功
        """
        for i, conn in enumerate(self.connections):
            if conn.get('name') == name:
                self.connections[i] = connection
                return self.save_config()
        return False
    
    def delete_connection(self, name: str) -> bool:
        """
        删除连接配置
        
        Args:
            name: 连接名称
            
        Returns:
            是否删除成功
        """
        for i, conn in enumerate(self.connections):
            if conn.get('name') == name:
                del self.connections[i]
                return self.save_config()
        return False
